from typing import Optional

from ylzagent import Component, Layer, config
from ylzagent.trace import tags
from ylzagent.trace.carrier import Carrier
from ylzagent.trace.context import get_context,NoopContext
from ylzagent.trace.span import NoopSpan
from ylzagent.trace.span import NoopSpan
from ylzagent.trace.tags import TagHttpMethod, TagHttpURL, TagHttpStatusCode, TagHttpParams,Tag
from ylzagent.plugins import ignore_http_request,tag_loggin_session,tag_return_value


def install():
    import quart
    from quart import Quart
    
    _full_dispatch_request = Quart.full_dispatch_request
    _handle_user_exception = Quart.handle_user_exception
    _handle_exception = Quart.handle_exception

    def params_tostring(params):
        return "\n".join([k + '=[' + ",".join(params.getlist(k)) + ']' for k, _ in params.items()])

    def __get_client_ip(request):
        '''
        获取客户端IP
        '''
        keys = ["x-forwarded-for", 'x-real-ip']
        for key, value in request.headers.items():
            if key.lower().strip() in keys:
                return value
        return request.remote_addr

    async def _sw_full_dispatch_request(this: Quart, request_context: Optional[quart.app.RequestContext] = None):
        import quart

        req = quart.request
        carrier = Carrier()
        method = req.method

        headers = req.headers
        cookies = req.cookies

        remote_add = __get_client_ip(req)
        remote_port = ""
        if "REMOTE_PORT" not in req.headers:
            remote_port = ""

        for item in carrier:
            if item.key.capitalize() in req.headers:
                item.val = req.headers[item.key.capitalize()]

        ignore = ignore_http_request(req.host, req.path.split('?')[0], method)
        if ignore:
            span = NoopSpan(NoopContext())
            print("dddddebug3")
        else:
            span = NoopSpan(NoopContext()) if config.ignore_http_method_check(method) \
                else get_context().new_entry_span(op=req.path, carrier=carrier, inherit=Component.General)
            
        with span:
            span.layer = Layer.Http
            span.component = Component.Flask
            span.peer = '%s:%s' % (
                remote_add,
                remote_port
            )
            
            
            span.tag(TagHttpMethod(method))
            span.tag(TagHttpURL(req.url.split("?")[0]))

            loggin_session = tag_loggin_session(req.host, req.path, method, headers, cookies)
            if loggin_session:
                span.tag(Tag(loggin_session['session'])).custom_key("session")
                span.tag(Tag(loggin_session['loginUser'])).custom_key("loginUser")

            values = await req.values
            
            
            if config.plugin_flask_collect_http_params and values:
                span.tag(TagHttpParams(params_tostring(req.values)[0:config.plugin_http_http_params_length_threshold]))
           
            resp = await _full_dispatch_request(this, request_context=request_context)

            if resp.status_code >= 400:
                span.error_occurred = True

            span.tag(TagHttpStatusCode(resp.status_code))

            return_value = tag_return_value(resp)
            if return_value != None:  ####
                span.tag(Tag(return_value).custom_key("return_value"))
            
            return resp

    def _sw_handle_user_exception(this: Quart, e):
        if e is not None:
            entry_span = get_context().active_span
            if entry_span is not None and type(entry_span) is not NoopSpan:
                entry_span.raised()

        return _handle_user_exception(this, e)

    async def _sw_handle_exception(this: Quart, e):
        if e is not None:
            entry_span = get_context().active_span
            if entry_span is not None and type(entry_span) is not NoopSpan:
                entry_span.raised()

        return await _handle_exception(this, e)

    Quart.full_dispatch_request = _sw_full_dispatch_request
    Quart.handle_user_exception = _sw_handle_user_exception
    Quart.handle_exception = _sw_handle_exception